/*
*  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
*  reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*  1. Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
*  2. Redistributions in binary form must reproduce the above copyright
*  notice, this list of conditions and thproe following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
*  3. The end-user documentation included with the redistribution,
*  if any, must include the following acknowledgment:
*  "This product includes software developed by the
*  Sun Microsystems, Inc. for Project JXTA."
*  Alternately, this acknowledgment may appear in the software itself,
*  if and wherever such third-party acknowledgments normally appear.
*
*  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
*  must not be used to endorse or promote products derived from this
*  software without prior written permission. For written
*  permission, please contact Project JXTA at http://www.jxta.org.
*
*  5. Products derived from this software may not be called "JXTA",
*  nor may "JXTA" appear in their name, without prior written
*  permission of Sun.
*
*  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
*  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*  SUCH DAMAGE.
*  ====================================================================
*
*  This software consists of voluntary contributions made by many
*  individuals on behalf of Project JXTA.  For more
*  information on Project JXTA, please see
*  <http://www.jxta.org/>.
*
*  This license is based on the BSD license adopted by the Apache Foundation.
*
*  $Id: Conversion.java,v 1.5 2006/07/12 21:24:30 nano Exp $
*/

package net.jxta.myjxta.util;

import java.awt.Color;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;

/**
 *
 * @version $Id: Conversion.java,v 1.5 2006/07/12 21:24:30 nano Exp $
 *
 * @author james todd [gonzo at jxta dot org]
 */

public class Conversion {

    private final static String BOGUS = "bogus";
    private final static char COLON = ':';
    private final static String ENCODING_UTF8 = "UTF-8";
    private final static String FILE_SCHEME = "file";
    private final static String RELATIVE_FILE_URI = FILE_SCHEME + COLON;
    public static char toChar(String s)
        throws ConversionException {
        char c = 0;

        try {
            c = s != null && s.length() >= 1 ?
                s.charAt(0) : BOGUS.charAt(0);
        } catch (IndexOutOfBoundsException ioobe) {
            throw new ConversionException(ioobe);
        }

        return c;
    }

    public static int toInt(String s)
        throws ConversionException {
        int i = -1;

        try {
            i = Integer.parseInt(s != null ? s : BOGUS);
        } catch (NumberFormatException nfe) {
            throw new ConversionException(nfe);
        }

        return i;
    }

    public static float toFloat(String s)
        throws ConversionException {
        float f = -1;

        try {
            f = Float.parseFloat(s != null ? s : BOGUS);
        } catch (NumberFormatException nfe) {
            throw new ConversionException(nfe);
        }

        return f;
    }

    public static boolean toBoolean(String s) {
        return Boolean.valueOf(s).booleanValue();
    }

    public static URL toURL(String s)
        throws ConversionException {
        if (s == null) {
            throw new ConversionException("null url");
        } else {
            StringBuffer sb = new StringBuffer(s.trim());
            
            for (int i = 0; i < sb.length(); i++) {
                if (Character.isWhitespace(sb.charAt(i))) {
                    sb.deleteCharAt(i--);
                }
            }
            
            s = sb.toString();
        }
        
        URL u = null;
        Exception e = null;

        try {
            u = new URL(s);
        } catch (MalformedURLException mue) {
            e = mue;
        }

        if (e != null) {
            try {
                u = new File(s).toURL();
            } catch (MalformedURLException mue) {
                throw new ConversionException(mue);
            }
        }

        return u;
    }

    public static URL toURL(File f)
        throws ConversionException {
        String protocol = "file";
        String delimiter = ":";
        String prefix = "./";
        String filePrefix = System.getProperty("file.seperator", "/");
        String s = f.toString();
	
        if (s.startsWith(filePrefix)) {
            s = prefix + s;
        }

        URL u = null;

        try {
            u = new URL(protocol + delimiter + s);
        } catch (MalformedURLException mue) {
            throw new ConversionException(mue);
        }

        return u;
    }

    public static List toURLs(List l)
        throws ConversionException {
        List<URL> urls = new ArrayList<URL>();

        try {
            for (Iterator i = l.iterator(); i.hasNext(); ) {
                urls.add(new URL((String)i.next()));
            }
        } catch (MalformedURLException mue) {
            throw new ConversionException(mue);
        }

        return urls;
    }

    public static Color toColor(String s)
        throws ConversionException {
        String octalPrefix = "0";
        String hex1Prefix = "0x";
        String hex2Prefix = "#";
        int decimalRadix = 10;
        int octalRadix = 8;
        int hexRadix = 16;
        int radix = decimalRadix;
        int i = -1;
        Exception e = null;

        if (s != null) {
            String t = s.toLowerCase();

            if (t.startsWith(hex1Prefix)) {
                s = s.substring(hex1Prefix.length());
                radix = hexRadix;
            } else if (t.startsWith(hex2Prefix)) {
                s = s.substring(hex2Prefix.length());
                radix = hexRadix;
            } else if (t.startsWith(octalPrefix)) {
                s = s.substring(octalPrefix.length());
                radix = octalRadix;
            } else {
                radix = decimalRadix;
            }

            try {
                i = Integer.parseInt(s, radix);
            } catch (NumberFormatException nfe) {
                e = nfe;
            }
        }

        if (i == -1 ||
            e != null) {
            throw new ConversionException(e);
        }

        return new Color(i);
    }

    public static Class toClass(String s)
        throws ConversionException {
        Class c = null;

        try {
            c = Class.forName(s);
        } catch (ClassNotFoundException cnfe) {
            throw new ConversionException(cnfe);
        }

        return c;
    }

    public static List toClasses(List l)
        throws ConversionException {
        List<Class<?>> classes = new ArrayList<Class<?>>();
	
        try {
            for (Iterator i = l.iterator(); i.hasNext(); ) {
                classes.add(Class.forName((String)i.next()));
            }
        } catch (ClassNotFoundException cnfe) {
            throw new ConversionException(cnfe);
        }

        return classes;
    }
    /**
     * Conversion of a {@link java.net.URI} of {@link java.lang.String} to it's
     * {@link java.io.File} equivalent.
     *
     * @param       u       provided {@link java.net.URI}
     * @return              {@link java.io.File} representation
     * @throws      ConversionException {@link net.jxta.ext.config.ConversionException}
     *                                  thrown when a conversion error occurs
     */
    
    public static File toFile(URI u)
    throws ConversionException {
        File f = null;

        if (u != null) {
            String s = u.getPath();

            if (s != null) {
            try {
                s = URLDecoder.decode(s, ENCODING_UTF8);
            } catch (UnsupportedEncodingException uee) {
                uee.printStackTrace();
            }
            } else if (u.getScheme().equalsIgnoreCase(FILE_SCHEME)) {
                s = u.toString().substring(RELATIVE_FILE_URI.length());
            }

            f = new File(s).getAbsoluteFile();
        } else {
            throw new ConversionException("invalid file");
        }

        return f;
    }
}
